<template>
  <div class="page-container">
    <!-- Logo部分 -->
    <div class="logo-container">
      <a href="/" class="nav-logo-link" aria-label="Amazon">
        <img src="@/assets/images/Amazon_logo.svg.webp" alt="Amazon" class="amazon-logo" />
      </a>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <div class="login-container">
        <!-- 重置密码框 -->
        <div class="a-box">
          <div class="a-box-inner">
            <h1 class="a-spacing-small">{{ $t('密码帮助') }}</h1>

            <form @submit.prevent="handleReset">
              <!-- 提示信息 -->
              <div class="verify-message">
                <span>{{ $t('输入您的电子邮件地址，我们会向您发送一个重置密码的链接。') }}</span>
              </div>

              <!-- 邮箱输入框 -->
              <div class="a-form-field">
                <label class="a-form-label">{{ $t('电子邮件') }}</label>
                <input
                  v-model="form.email"
                  type="email"
                  ref="emailInput"
                  class="a-input-text"
                  :class="{ 'a-form-error': formError }"
                  :placeholder="$t('请输入邮箱地址')"
                  @blur="() => {
                    if (form.email && !validateEmail(form.email)) {
                      formError = true
                      errorMessage = $t('请输入正确的邮箱格式')
                      ElMessage.error(errorMessage)
                    }
                  }"
                />
                <div v-if="formError" class="a-alert-error">
                  {{ errorMessage }}
                </div>
              </div>
              <div class="a-form-field">
                <label class="a-form-label">{{ $t('验证码') }}</label>
                <input
                  v-model="form.code"
                  type="code"
                  ref="emailInput"
                  class="a-input-text"
                  :class="{ 'a-form-error': formError }"
                  :placeholder="$t('请输入验证码')"
                  @blur="() => {
                    if (form.code && !validatecode(form.code)) {
                      formError = true
                      errorMessages = $t('请输入验证码')
                      ElMessage.error(errorMessages)
                    }
                  }"
                />
                <div>
                  <el-button link :disabled="countdown > 0" @click="handleResend" style="color: #f0c14b;">
                      {{ countdown > 0 ? `${$t('重新发送')} (${countdown}s)` : $t('发送验证码') }}
                    </el-button>
                </div>
                <div v-if="formError" class="a-alert-error">
                  {{ errorMessages }}
                </div>
              </div>
              <div class="a-form-field">
                <label class="a-form-label">{{ $t('新密码') }}</label>
                <input
                  v-model="form.password"
                  type="password"
                  ref="emailInput"
                  class="a-input-text"
                  :class="{ 'a-form-error': formError }"
                  :placeholder="$t('请输入新密码')"
                  @blur="() => {
                    if (form.password && !validatePassword(form.password)) {
                      formError = true
                      errorMessage = $t('请输入新密码')
                      ElMessage.error(errorMessage)
                    }
                  }"
                />
                <div v-if="formError" class="a-alert-error">
                  {{ errorMessage }}
                </div>
              </div>
              <!-- 继续按钮 -->
              <button
                type="submit"
                class="a-button-primary"
                :disabled="isLoading"
              >
                {{ $t('继续') }}
              </button>

              <!-- 返回登录 -->
              <div class="a-divider-inner"></div>
              <div class="back-section">
                <router-link to="/login" class="a-link-normal">{{ $t('返回登录') }}</router-link>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>

    <!-- 页脚 -->
    <Footer />
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import Footer from '../components/Footer.vue'
import {useI18n} from "vue-i18n";
const { t } = useI18n();
import { ApiConfig } from "@/api/common";
import { memberforgetP } from "@/api/mine";

import { ApiSendEmail } from '@/api/public'


const router = useRouter()
const emailInput = ref<HTMLInputElement | null>(null)
const isLoading = ref(false)
const formError = ref(false)
const errorMessage = ref('')
const errorMessages = ref('')

const form = reactive({
  email: '',
  code: '',
  password:''
})
const GETCODE_SETTING = ref({
   //Google验证码开关
    googleCode : false,
    //登录图形验证码开关
    captcha : false,
    //h5邀请码开关
    inviteCode : false,
    //手机号格式开关
    phoneValid : false,
    //资金密码开关
    walletPasswordValid : false,
    //短信邮箱开关
    smsOrEmailOtp : false
})
const handleResend = async () => {
  try {
    if (!form.email) {
      formError.value = true
      errorMessage.value = t('请输入邮箱地址')
      ElMessage.error(errorMessage.value)
      return
    }
    await new Promise(resolve => setTimeout(resolve, 500))
    startCountdown('current')
  } catch (error) {
    ElMessage.error(t('发送失败，请重试'))
  }
}
//发送验证码
const countdown = ref(0)
const newEmailCountdown = ref(0)
const startCountdown = async (type: 'current' | 'new') => {
  ApiSendEmail({email: form.email}).then(res => {
    ElMessage.success(res.msg || t('验证码已发送'))
    const target = type === 'current' ? countdown : newEmailCountdown
    target.value = 60
    const timer = setInterval(() => {
      target.value--
      if (target.value <= 0) clearInterval(timer)
    }, 1000)
  }).catch(() => {
    ElMessage.error(t('发送失败'))
  })
}
onMounted(() => {
  // emailInput.value?.focus();
  ApiConfig({
    key: 'CODE_SETTING'
  }).then(res => {
    GETCODE_SETTING.value = res.data
  })
})

// 邮箱验证函数
const validateEmail = (email: string) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return emailRegex.test(email)
}
const validatePassword = (password) => {
  if (password == '') {
    return false
  }else{
    return true
  }
}
const validatecode = (code) => {
  if (code == '') {
    return false
  }else{
    return true
  }
  
}
const handleReset = async () => {
  try {
    if (!form.email) {
      formError.value = true
      errorMessage.value = t('请输入邮箱地址')
      ElMessage.error(errorMessage.value)
      return
    }

    if (!validateEmail(form.email)) {
      formError.value = true
      errorMessage.value = t('请输入正确的邮箱格式')
      ElMessage.error(errorMessage.value)
      return
    }
    if (!validatecode(form.code)) {
      formError.value = true
      errorMessages.value = t('请输入验证码')
      ElMessage.error(errorMessages.value)
      return
    }
    if (!validatePassword(form.password)) {
      formError.value = true
      errorMessages.value = t('请输入新密码')
      ElMessage.error(errorMessages.value)
      return
    }
//     const form = reactive({
//   email: '',
//   code: '',
//   password:''
// })
    // let obj = {
    //   email:form.code,
    //   code::form.code,
    // }
    memberforgetP(form).then(res=>{
      if(res.code == 200){
        ElMessage.success(t('设置成功'))
        router.push('/login')
      }
    })
    
    isLoading.value = true
    // 模拟API调用
    // await new Promise(resolve => setTimeout(resolve, 1000))
    // ElMessage.success(t('重置链接已发送到您的邮箱'))
    // router.push('/login')
  } catch (error) {
    formError.value = true
    errorMessage.value = t('发送失败，请重试')
    ElMessage.error(errorMessage.value)
  } finally {
    isLoading.value = false
  }
}
</script>

<style lang="scss" scoped>
.page-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #fff;
}

.logo-container {
  padding: 14px 0 10px;
  text-align: center;
}

.main-content {
  flex: 1;
  display: flex;
  justify-content: center;
  width: 100%;
  max-width: 1500px;
  margin: 0 auto;
}

.login-container {
  width: 350px;
}

.a-box {
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: #fff;

  .a-box-inner {
    padding: 25px 27px;
  }
}

.a-spacing-small {
  font-size: 28px;
  line-height: 1.2;
  font-weight: 400;
  margin-bottom: 18px;
}

.verify-message {
  font-size: 13px;
  line-height: 19px;
  margin-bottom: 14px;
}

.a-form-field {
  margin-bottom: 26px;
}

.a-form-label {
  display: block;
  padding-left: 2px;
  padding-bottom: 2px;
  font-weight: 700;
  font-size: 14px;
  line-height: 19px;
}

.a-input-text {
  width: 100%;
  height: 31px;
  padding: 3px 7px;
  line-height: normal;
  border: 1px solid #a6a6a6;
  border-radius: 3px;
  box-shadow: 0 1px 0 rgba(0,0,0,.07) inset;
  font-size: 13px;

  &:focus {
    border-color: #e77600;
    box-shadow: 0 0 3px 2px rgba(228,121,17,.5);
  }

  &.a-form-error {
    border-color: #d00;
    box-shadow: 0 0 0 3px rgba(221,0,0,.1) inset;
  }
}

.a-alert-error {
  margin-top: 4px;
  color: #c40000;
  font-size: 12px;
}

.a-button-primary {
  width: 100%;
  height: 31px;
  font-size: 13px;
  background: #f4d078;
  background: linear-gradient(to bottom, #f7dfa5, #f0c14b);
  border: 1px solid;
  border-color: #a88734 #9c7e31 #846a29;
  border-radius: 3px;
  cursor: pointer;

  &:hover {
    background: linear-gradient(to bottom, #f5d78e, #eeb933);
  }

  &:disabled {
    background: #f9f9f9;
    border-color: #e7e7e7;
    cursor: not-allowed;
  }
}

.a-divider-inner {
  height: 1px;
  background-color: #ddd;
  margin: 14px 0;
}

.back-section {
  text-align: center;
}

.a-link-normal {
  color: #0066c0;
  text-decoration: none;

  &:hover {
    color: #c45500;
    text-decoration: underline;
  }
}

.amazon-logo {
  width: 103px;
  height: 31px;
  object-fit: contain;
}

.nav-logo-link {
  display: inline-flex;
  justify-content: center;
  text-decoration: none;
  padding: 0;
  height: 31px;
}


// 响应式设计
@media (max-width: 768px) {
  .login-container {
    width: 90%;
    max-width: 400px;
  }
}
</style>
